require "rMAL/version"
require "yaml"
require "ox"

module RMAL
	# Configuration of password, username and apikey, for use by other modules
	module Settings
		# Create the settings.yml file
		def self.init(dir = "/") # Default dir may not have the correct access rights granted
			# Allows user to not bother with the trailing / if so desired
			if !(dir.end_with? "/")
				dir = dir + "/"
			end
			# Create a settings.yml file
			File.open("#{dir}settings.yml", "w") do |file|
			end
			# Create global path variable for ease of use
			$path = "#{dir}/settings.yml"
		end
		# Allows the user to change the settings where necessary (and rMAL where necessary)
		def self.set(username, password, apikey)
			configuration = {
				'username' => username,
				'password' => password,
				'apikey' => apikey
			}
			open($path, 'w') { |f| YAML.dump(configuration, f) }
			open($path) { |f| return f.read }
		end
		# Load the settings for use in other modules
		public # I know this isn't necessary, will remove later

		def self.load(path)
			# Load the file
			settings = YAML::load_file path
			# I am aware of the serious security implications of this eval(). This needs a better fix ASAP.
			working = eval(settings.inspect)
			# Load the settings into working variables
			$w_username = working["username"]
			$w_password = working["password"]
			$w_apikey = working["apikey"]
		end
	end
	# Verify Credentials
	def self.login
		RMAL::Settings.load($path)
		# Curl into MAL with the request
		IO.popen("curl -u #{$w_username}:#{$w_password} http://myanimelist.net/api/account/verify_credentials.xml -A #{$w_apikey}") { |f| $login_response = f.read }
		# Parse out the user id
		login_id = Ox.parse($login_response).user.id.text
		# Parse out the username
		login_username = Ox.parse($login_response).user.username.text
		# Display both bits of info
		puts "Login ID: " + login_id, "Login Username: " + login_username
		# Return both bits of info
		return login_id, login_username
	end
	# Search anime/manga
	def self.search(type = "anime", query)
		RMAL::Settings.load($path)
		# Replace spaces with '+'s
		query = query.gsub(/\s/, "+")
		# Curl into MAL with the request
		IO.popen("curl -u #{$w_username}:#{$w_password} http://myanimelist.net/api/#{type}/search.xml?q=#{query} -A #{$w_apikey}") { |f| $search_response = f.read }
		p $search_response # temporary
	end
end

# Not done yet